package com.wb.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.HashMap

/**
 * 气象查询
 *
 * @author 祁雪
 */
class WeatherUtil {

    companion object {

        val API_MAP = hashMapOf(
            /**
             * 搜索城市代码
             * https://weather.cma.cn/api/autocomplete
             * q: 城市名称
             * limit: 返回条数 建议填写10
             * timestamp: 时间戳
             */
            "city" to "https://weather.cma.cn/api/autocomplete",
            /**
             * 获取城市天气
             * https://weather.cma.cn/api/weather/view
             * stationid: 城市代码（由上方api获取）不填则默认ip城市位置
             */
            "weather" to "https://weather.cma.cn/api/weather/view"
        )

        /**
         * 获取天气
         * @return 返回文字消息
         */
        fun getWeather(city: String): ArrayList<String> {
            println("开始读取${city}气象地址")
            var param = hashMapOf(
                "q" to city,
                "limit" to "10",
                "timestamp" to System.currentTimeMillis().toString()
            )

            var result = RestUtil.sendGet(
                API_MAP.get("city")!!, param
            )

            val gson = Gson()

            var map = gson.fromJson(
                result,
                object : TypeToken<HashMap<String, Any>>() {}.type
            ) as HashMap<String, Any>

            if (map.containsKey("data")) {
                val list = gson.fromJson(
                    gson.toJson(map.get("data")),
                    object : TypeToken<ArrayList<String>>() {}.type
                ) as ArrayList<String>

                if (list.size == 0) {
                    return arrayListOf("暂未搜索到【${city}】的气象地址")
                }

                val cityCode = list.get(0).split("|")[0]
                println("开始读取${city}天气信息")

                param = hashMapOf(
                    "stationid" to cityCode
                )

                result = RestUtil.sendGet(API_MAP.get("weather")!!, param)

                map = gson.fromJson(
                    result,
                    object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                if (map.containsKey("data")) {

                    val weatherData = gson.fromJson(
                        gson.toJson(map.get("data")),
                        object : TypeToken<WeatherData>() {}.type
                    ) as WeatherData

                    if (weatherData.now == null) {
                        return arrayListOf("暂未搜索到【${city}】的气象信息")
                    }

                    val msgs = arrayListOf<String>(
                        if (weatherData.location != null) {
                            weatherData.location!!.path
                        } else city,
                        "当前温度: ${weatherData.now!!.temperature}℃  ${weatherData.now!!.windDirection} ${weatherData.now!!.windScale}",
                        "气压: ${weatherData.now!!.pressure}hPa    相对湿度: ${weatherData.now!!.humidity}%"
                    )

                    if (weatherData.daily.size > 0) {
                        val daily = weatherData.daily[0]

                        msgs.add("最高气温: ${daily.high}℃")
                        msgs.add("最低气温: ${daily.low}℃")
                        msgs.add("白天: ${daily.dayText}    夜晚: ${daily.nightText}")

                    }

                    val afterMsg = arrayListOf<String>()
                    for (i in 1..2) {
                        if (weatherData.daily.size > i) {
                            val daily = weatherData.daily[i]
                            afterMsg.add(if (i == 1) "【明天】" else if (i == 2) "【后天】" else daily.date)
                            afterMsg.add("最高气温: ${daily.high}℃")
                            afterMsg.add("最低气温: ${daily.low}℃")
                            afterMsg.add("白天: ${daily.dayText}    夜晚: ${daily.nightText}")
                        }
                    }

                    val alarmMsgs = arrayListOf<String>()
                    if (weatherData.alarm.size > 0) {
                        // 取最后一条
                        alarmMsgs.add("【预警】")
                        alarmMsgs.add(weatherData.alarm.get(0).title)
                    }
                    return arrayListOf(
                        msgs.joinToString(separator = "\n"),
                        afterMsg.joinToString(separator = "\n"),
                        alarmMsgs.joinToString(separator = "\n")
                    )
                }
            }

            return arrayListOf("暂未搜索到【${city}】的气象信息")
        }

    }

    class WeatherData {

        var location: Location? = null

        var daily: List<Daily> = listOf()

        var now: Now? = null

        var alarm: List<Alarm> = listOf()

        var lastUpdate = ""

        class Location {
            var id: String = ""

            var name = ""

            var path = ""

            // 经度
            var longitude: Double = 0.0

            // 纬度
            var latitude = 0.0

            // 时区
            var timezone = 0.0
        }

        class Daily {
            var date = ""

            // 最高温度
            var high = 0.0

            // 最低气温
            var low = 0.0

            // 白天天气
            var dayText = ""

            var dayCode = 0

            // 晚上天气
            var nightText = ""

            var nightCode = 0

            // 白天风向
            var dayWindDirection = ""

            var dayWindScale = ""

            // 晚上风向
            var nightWindDirection = ""

            var nightWindScale = ""
        }

        class Now {
            // 当前气温
            var temperature = 0.0

            // 当前气压
            var pressure = 0.0

            // 相对湿度
            var humidity = 0.0

            // 风向
            var windDirection = ""

            var windScale = ""

            // 风速
            var windSpeed = 0.0

            // 降水量 mm 如果是9999 则显示为 --
            var precipitation = 0.0
        }

        // 报警
        class Alarm {

            var id = ""

            var title = ""

            // 信号类型
            var signaltype = ""

            // 信号等级
            var signallevel = ""

            // 生效时间
            var effective = ""

            var eventType = ""

            var severity = ""

        }

        override fun toString(): String {
            return "WeatherData(location=$location, daily=$daily, now=$now, alarm=$alarm, lastUpdate='$lastUpdate')"
        }

    }

}

fun main() {
    println(WeatherUtil.getWeather("南京"))
}